package com.stylefeng.guns.modular.vpn.utils;

import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.modular.vpn.config.properties.SftpProperties;
import com.stylefeng.guns.modular.vpn_server_info.controller.VpnServerController;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * @Description 文件工具
 * @Author Mr.God
 * @Date 2020-03-21 15:53
 **/
public class FileUtil {

    private final static Logger logger = LoggerFactory.getLogger(VpnServerController.class);

    public static String uploadFile(MultipartFile file, SftpProperties imageSftp){
        logger.info("开始上传服务器节点图标>>>>>>>>");
        SftpUtil imageUtil = null;
        String remoteFile = "";
        try {
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            remoteFile = imageSftp.getBasePath() + uuid + SftpUtil.getExtName(file.getOriginalFilename());
            imageUtil = new SftpUtil(imageSftp);

            imageUtil.uploadFile(remoteFile,file.getInputStream());

        } catch (Exception e) {
            logger.error("服务器节点图标上传出错，请重试....");
            e.printStackTrace();
            throw new GunsException(BizExceptionEnum.VPN_UPLOAD_FILE_ERROR);
        }finally {
            if (imageUtil != null){
                imageUtil.close();
            }
        }

        logger.info("服务器节点图标上传完成<<<<<<<<<<");
        if(StringUtils.isNotEmpty(remoteFile)){
            String[] filePaths  = remoteFile.split("html");
            remoteFile = filePaths[1];
        }

        return  remoteFile;
    }
}
